#-*- coding:UTF-8 -*-
#内部函数，内嵌函数
'''
Created on 2013-6-5

@author: Administrator
'''
#406页
import chapter11 as ch11
from time import ctime, sleep, time
def t():
    ''''''
    a = 1
    print a
#定义内部函数
def foo():
    def bar():
        print 'bar() called'
    
    print 'foo() called'
    bar()
    return bar

b = foo()
b()

#装饰器的例子
class MyClass():
    def staticFoo():
        print 'staticFoo'
    staticFoo = staticmethod(staticFoo)
    
MyClass.staticFoo()

    
#偏函数
from operator import add, mul
from functools import partial

add1 = partial(add, 1)
mul100 = partial(mul, 100)

print add1(10)
print add1(1)
print mul100(10)
print mul100(500)

baseTwo = partial(int, base=2)
print baseTwo('10010')

#作用域
is_this_global = 'xyz'
def foo2():
    global is_this_global
    this_is_local = 'abc'
    is_this_global = 'def'
    
    print this_is_local + is_this_global
foo2()

#闭包，关于使用定义在其他作用域的变量
def counter(start_at = 0):
    count = [start_at]
    def inc():
        count[0] += 1
        return count[0]
    return inc
#追踪闭关变量
output = '<int %r id=%#0x val=%d>'
w = x = y = z = 1

def f1():
    x = y = z = 2
    def f2():
        y = z = 3
def f3():
    z = 4
print output % ('w', id(w), w)
print output % ('x', id(x), x)
print output % ('y', id(y), y)
print output % ('z', id(z), z)

clo = f3.func_closure
if clo:
    print 'f3 closure vars:', [str(c) for c in clo]
else:
    print 'no f3 closure vars'
f3()

#clo = f1().f2.func_closure
if clo:
    print 'f2 closure vars:', [str(c) for c in clo]
else:
    print 'no f2 closure vars'
#f1().f2()

clo = f1.func_closure
if clo:
    print 'f1 clocure vars:', [str(c) for c in clo]
else:
    print 'no f1 closure vars'
f1()
    
print time()
def logged(when):
    def log(f, *args, **kargs):
        print ''' Called:
            function: %s
            args: %r
            kargs: %r''' % (f, args, kargs)
    def pre_logged(f):
        def wrapper(*args, **kargs):
            log(f, *args, **kargs)
            return f(*args, **kargs)
        return wrapper
    
    def post_logged(f):
        def wrapper(*args, **kargs):
            now = time()
            try:
                return f(*args, ** kargs)
            finally:
                log(f, *args, ** kargs)
                print 'time delta: %s' % (time() - now)
        return wrapper
    try:
        return {"pre": pre_logged, "post": post_logged}[when]
    except KeyError, e:
        raise ValueError(e), 'must be "pre" or "post"'
@logged('post')
def hello(name):
    print "Hello, ", name

hello('hanjiewu')

def tsfunc(func):
    def wrappedFunc(tips):
        print '[%s] %s() called' % (ctime(), func.__name__)
        return func(tips)
    return wrappedFunc

@tsfunc
def foo1(tips):
    print tips

foo1('hanjiewu')